<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/2
 * Time: 21:03
 */

namespace app\api\service;
use app\api\model\Book;
use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use think\Db;
use think\Exception;

/*
 * 检查库存
 * 减库存
 * 告知微信服务器  收到消息
 * */
Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class WxNotify extends \WxPayNotify
{
    public function NotifyProcess($data, &$msg)
    {
        // 支付成功
        if($data['result_code'] == 'SUCCESS')
        {
            Db::startTrans();
            try{
                $orderNo = $data['out_trade_no'];
                $orderModel = OrderModel::where('order_no','=', $orderNo)->find();

                if($orderModel->status==OrderStatusEnum::UNPAID)
                {
                    // 检查库存
                    $orderService = new OrderService();
                    $orderState = $orderService->checkOrderState($data['out_trade_no']);
                    if($orderState['pass']){
                    // 减库存
                        $this->reduceStock($orderState['bookStatusArray']);
                        // 改status
                        $this->updateStatus($orderModel->id,true);
                    }else{
                        // 改status
                        $this->updateStatus($orderModel->id,false);
                    }
                }
                Db::commit();
                //  告知微信服务器  收到支付成功的消息
                return true;
            }

            catch (Exception $exception)
            {
                // 支付成功  但是数据库没有更新  返回false 微信服务器就会一直发送支付成功的信息
                Db::rollback();
                Log::record($exception);
                return false;
            }
        } else{
            //  告知微信服务器  收到支付失败的消息
            return true;
        }
    }

    private function reduceStock($bookStatusArray){
        foreach ($bookStatusArray as $book){
            Book::where('id','=',$book['id'])->setDesc('stock',$book['count']);
        }
    }

    private function updateStatus($orderId,$pass)
    {
        $status = $pass ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF;
        OrderModel::where('id','=',$orderId)->update(['status'=>$status]);
    }
}